import cookies from 'js-cookies'

import store from '@/store';
import Nprogress from 'nprogress';
import request from '@/api/request.js';

/**
 * @description: 延迟一定的时间函数，用于模拟网络请求的延迟过程
 * @param {*}
 * @return {*}
 */
export async function delay() {
  return await new Promise((resolve) => {
    setTimeout(() => {
      resolve()
    }, 2000)
  })
}

// cookie 的 key
let userKeys = ['username', 'appkey', 'email', 'role'];

/**
 * @description: 设置用户标记 cookie
 * @param {*} parmes
 * @return {*}
 */
export function setCookies(parmes) {
  let arr = Object.entries(parmes)
  arr.forEach(([key, value]) => {
    cookies.setItem(key, value)
  })
}

/**
 * @description: 删除登录标记的 cookies
 * @param {*}
 * @return {*}
 */
export function removeCookies() {
  userKeys.forEach((it) => {
    let data = cookies.removeItem(it);
    console.log(it);
  })
}

/**
 * @description: 查询登录标记是否存在
 * @param {*}
 * @return {*}
 */
export function hasCookies() {
  return userKeys.every((it) => {
    return cookies.hasItem(it)
  })
}

/**
 * @description: 获取登录标记
 * @param {*}
 * @return {*}
 */
export function getCookies() {
  let obj = {}
  userKeys.forEach((it) => {
    let str = cookies.getItem(it)
    obj[it] = str ? str : ''
  })
  return obj
}

// 角色的管理权限
const rulesUser = {
  admin: ['Count', 'Goods', 'GoodAdd', 'GoodList','GoodEdit', 'Cate', 'CateList', 'UserList', 'User'],
  coustomer: ['Count', 'Goods', 'GoodAdd', 'GoodList','GoodEdit', 'Cate', 'CateList']
}

/**
 * @description: 筛选需要展示的路由
 * @param {*} role 角色权限
 * @param {*} rules 需要筛选的数组
 * @return {*}
 */
export function filterMenu(role, rules) {
  let mapRule = (rules) => {
    let arr = []
    for (let i = 0; i < rules.length; i++) {
      let it = rules[i]
      let key = rulesUser[role].indexOf(it.name) !== -1 || !it.name;
      if (key) {
        let children = it.children
        if (children) {
          children = mapRule(children)
        }
        arr.push({
          ...it,
          children
        })
      }
    }
    return arr;
  }
  let filterRule = mapRule(rules).filter((it) => it)
  return filterRule
}

/**
 * @description: 发送请求阶段的处理
 * @param {*} url 请求地址
 * @param {*} type 请求方式
 * @param {*} params 传递的数据
 * @return {*}
 */
export async function fetchData(url, type, params) {
  store.commit("changeLoginState", true);

  Nprogress.start();
  let config = {
    url,
    method: type,
  };
  if(type === 'get'){
    config = {
      params,
      ...config
    }
  } else {
    config = {
      data : {
        ...params
      },
      ...config
    }
  }
  let data = await request(config)
  store.commit("changeLoginState", false);
  Nprogress.done();
  return data;
}

export function setDateFormat(str){
  let date = new Date(str);

  let year = date.getFullYear();
  let months = date.getMonth() + 1;
  let day = date.getDate();
  let hour = date.getHours();
  let minutes = date.getMinutes();
  return `${year}-${months}-${day} ${hour}:${minutes}分`
}